<template>
  <div id="interMethodOutParamDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" @click="getOutParamList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="同步出参" v-if="detailList.length <= 0" @click="syncOutParams"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="复制" @click="copy"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="粘贴" @click="paste"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveBathInterfaceParam"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteInterfaceParam"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-upload" v-show="buttonName" :content="buttonName" @click="upload"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="InterfaceParamTableRef" class="mytable-scrollbar" :data="detailList" border="inner" align="left" height="auto" :row-config="{ isCurrent: true, isHover: true }" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" :expand-config="{ expandAll: true, reserve: true }" :tree-config="{
        expandAll: true,
        transform: true,
        rowField: 'paramId',
        parentField: 'paramParentId'
      }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column type="seq" width="0" title=" "></vxe-column>
        <vxe-column field="outCode" title="外源参数" tree-node width="150" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.outCode" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="code" title="字段名" :edit-render="{}" width="150">
          <template #edit="{ row, rowIndex }">
            <VxePulldownSelection :isChild="true" :childIndex="row.id" :ref="'fieldRef' + rowIndex" :url="'/api/sys/getInterfaceDictParamList'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
              { field: 'code', title: '字段' },
              { field: 'common', title: '出参名称' }
            ]" :aimKeys="[
              { aimKey: 'code', rowKey: 'code' },
              { aimKey: 'outCode', rowKey: 'outCode' },
              { aimKey: 'coloumType', rowKey: 'coloumType' },
              { aimKey: 'common', rowKey: 'common' },
            ]" :displayTexts="['common']" :displayTextObj="row.common ? row.common : ''" :dataObj="{ dictId: interfaceDictId, type: 2 }" />
          </template>
        </vxe-column>
        <vxe-column field="coloumType" title="字段类型" :edit-render="{}" width="100">
          <template #default="{ row }">
            <span>{{ formatCommon(coloumTypeList, row.coloumType) }}</span>
          </template>
          <template #edit="{ row }">
            <vxe-select v-model="row.coloumType" transfer>
              <vxe-option v-for="item in coloumTypeList" :key="item.id" :value="item.code" :label="item.name"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>

        <vxe-column field="common" title="字段说明" width="200">
          <template #edit="{ row }">
            <vxe-input v-model="row.common" placeholder type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="state" title="是否启用" width="80" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.state" inline-prompt active-text="是" inactive-text="否"></el-switch>
          </template>
        </vxe-column>
        <vxe-column field="isFixed" title="是否固定值" width="100" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.isFixed" inline-prompt active-text="是" inactive-text="否"></el-switch>
          </template>
        </vxe-column>
        <vxe-column field="paramCompare" title="参数对照" width="100">
        </vxe-column>
        <vxe-column title="操作" align="center">
          <template #default="{ row, rowIndex }">
            <vxe-button type="text" status="primary" icon="vxe-icon-edit" circle @click="handleUpdate(row, rowIndex)"> </vxe-button>
            <!-- <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="handleDelete(row)"> </vxe-button> -->
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-modal class-name="animation-slide-right" destroy-on-close v-if="moduleDialog1" v-model="moduleDialog1" title="添加参数映射" width="30vw" height="40vh" show-zoom resize>
        <vxe-button content="新增" type="text" class="button-blue" icon="vxe-icon-add" @click="paramCompareAdd"> </vxe-button>
        <vxe-button content="保存" type="text" class="button-blue" icon="vxe-icon-save" @click="paramCompareSave"> </vxe-button>
        <vxe-table ref="refParamCompare" border resizable show-overflow :data="paramComoareList" :edit-config="{ trigger: 'click', mode: 'cell' }">
          <vxe-column type="seq" width="60"></vxe-column>
          <vxe-column field="sourceValue" title="源值" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row }">
              <vxe-input v-model="row.sourceValue" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="targetValue" title="目标值" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.targetValue" type="text" placeholder="请输入目标值"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column title="操作" align="center">
            <template #default="{ row, rowIndex }">
              <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="handleParamCompareDelte(rowIndex)"> </vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </vxe-modal>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { IsEmpty } from '@/utils/common';
import { AppStore } from '@/stores/store';
import { VXETable } from 'vxe-table';
import { camelCase } from 'lodash';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';

let store = AppStore();
defineExpose({ initPage });
let methodId = ref(null);
let moduleDialog1 = ref(false);
let interfaceDictId = ref(null);
let interfaceParamId = ref(null);
let interfaceType = ref(null);
let detailList: any = reactive([]);
let rloading = ref(false);
let coloumTypeList = reactive([]);
let flag = ref(true);
let interfaceId: any = ref(null);
let paramComoareList = reactive([]);
let buttonName = ref('');

function initPage(row: any) {
  methodId.value = row.id;
  interfaceDictId.value = row.interfaceDictId;
  interfaceId.value = row.interfaceId;

  if (row.dataType == 'WEB') {
    buttonName.value = '导入XML模板';
  } else if (row.dataType == 'JSON') {
    buttonName.value = '导入JSON模板';
  } else if (row.dataType == 'HL7') {
    buttonName.value = '导入HL7模板';
  } else {
    buttonName.value = '';
  }

  getOutParamList();
  //获取字典配置的出参
  getDictItemsList();
}
function getOutParamList() {
  rloading.value = true;
  detailList.length = 0; //放入数据前清空数据
  const url = '/api/sys/sysInterfaceMethodOutParam/findInterfaceDictOutParamList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { interfaceId: interfaceId.value, methodId: methodId.value }
    })
    .then((res: any) => {
      console.log(res.data.methodList);
      if (res.data.methodList && res.data.methodList.length > 0) {
        flag.value = true;
        detailList.push(...res.data.methodList);
      } else {
        flag.value = false;
        detailList.push(...res.data.dictList);
      }
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取出参异常', VxeNotifyType.error);
    });
}

async function upload() {
  const { file } = await VXETable.readFile();
  uploadByUrl(file);
}
function uploadByUrl(file) {
  let url = '/api/sys/sysInterfaceMethod/uploadJsonInterfaceMethodOutParam';
  const fd = new FormData();
  fd.append('file', file);
  fd.append('interfaceId', interfaceId.value);
  fd.append('interfaceMethodId', methodId.value);
  fd.append('interfaceDictId', interfaceDictId.value);
  proxy.$http
    .post(url, fd)
    .then((res: any) => {
      console.log(res);
      if (res.status.code == 1) {
        getOutParamList();
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err) => {
      console.log(err);
      VxeMessage(err, VxeNotifyType.error);
    });
}

async function paramCompareAdd(): Promise<void> {
  const record = {
    targetValue: '',
    sourceValue: ''
  };
  paramComoareList.push(record);
}

async function paramCompareSave() {
  moduleDialog1.value = false;
  const data = detailList.filter((p) => p.id == curId.value);
  data[0].paramCompare = JSON.stringify(paramComoareList);
}
let curId = ref('');
function handleUpdate(row) {
  curId.value = row.id;
  paramComoareList.length = 0;
  console.log(row.paramCompare);
  Object.assign(paramComoareList, row.paramCompare ? JSON.parse(row.paramCompare) : []);
  moduleDialog1.value = true;
}

function handleParamCompareDelte(index) {
  paramComoareList.splice(index, 1);
}

//批量获取字典
async function getDictItemsList() {
  coloumTypeList.length = 0;
  let dictTreeTypeCodes: any = ['interfaceColoumType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const severityType = dictTreeTypeItems.data.find((item) => item.code === 'interfaceColoumType');
  coloumTypeList.push(...severityType.detailDataList);
}

// 左侧保存
async function saveBathInterfaceParam() {
  if (IsEmpty(methodId.value)) {
    VxeMessage('请选择方法', VxeNotifyType.error);
  } else {
    const sveOrupdateDetail = [] as any[];
    detailList.forEach((e: any) => {
      const iDetail: any = {
        id: flag.value ? e.id : '',
        seq: e.seq,
        interfaceId: interfaceId.value,
        methodId: methodId.value,
        outCode: e.outCode,
        code: e.code,
        common: e.common,
        type: e.type,
        coloumType: e.coloumType,
        state: e.state,
        orgId: e.orgId,
        isFixed: e.isFixed,
        paramId: e.paramId,
        paramParentId: e.paramParentId,
        paramCompare: e.paramCompare
      };
      sveOrupdateDetail.push(iDetail);
    });
    if (sveOrupdateDetail.length > 0) {
      const url = '/api/sys/sysInterfaceMethodOutParam/saveOrUpdateInterfaceMethodOutParam';
      const obj: any = {};
      obj.datas = sveOrupdateDetail;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          getOutParamList();
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  }
}

// 左侧删除
async function deleteInterfaceParam() {
  const sltDetails = (proxy.$refs.InterfaceParamTableRef as any).getCheckboxRecords();
  if (!(sltDetails.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    const type = await VXETable.modal.confirm('确定要删除当前勾选的数据？');
    if (type === 'confirm') {
      //后台删除数据
      const delDetailList = sltDetails.filter((p: any) => !IsEmpty(p.id));
      if (delDetailList.length > 0) {
        const data = { ids: delDetailList.map((p) => p.id) };
        const url = '/api/sys/sysInterfaceMethodOutParam/deleteBatchInterfaceMethodOutParam';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            getOutParamList();
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      }
      //页面删除未保存的数据
      const removeDetailList = sltDetails.filter((p: any) => IsEmpty(p.id));
      if (removeDetailList.length > 0) {
        // 删除的新增的空白数据 不走接口
        let $Xtable = proxy.$refs.InterfaceParamTableRef;
        if ($Xtable) {
          for (const removeRow of removeDetailList) {
            detailList.splice(removeRow.seq - 1);
          }
        }
      }
    }
  }
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
/**同步出参 */
function syncOutParams() {
  const url = '/api/sys/getInterfaceDictParamList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { dictId: interfaceDictId.value, type: '2' }
    })
    .then((res: any) => {
      res.data.forEach((e) => {
        const a = {
          interfaceId: interfaceId.value,
          methodId: methodId.value,
          outCode: null,
          code: e.code,
          seq: e.seq,
          coloumType: e.coloumType,
          common: e.common,
          state: e.state,
          paramId: e.id,
          paramParentId: e.parentId
        };
        detailList.push(a);
      });
    })
    .catch((err: any) => {
      VxeMessage('请选择场景', VxeNotifyType.error);
    });
}
/**复制 */
function copy() {
  VxeMessage('已复制到剪贴板', VxeNotifyType.success);
  sessionStorage.setItem('busoutparamcopy', JSON.stringify(detailList));
}

/**入参字段选中事件 */
function pulldownSelectConfirm(e) {
  if (e.isChild) {
    e.aimKeys.forEach((m) => {
      const data = detailList.filter((p) => p.id == e.childIndex);
      console.log(data);
      detailList.filter((p) => p.id == e.childIndex)[0][m.aimKey] = e.row[m.rowKey];
      // tableList[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  }
}

/**粘贴 */
function paste() {
  const a = sessionStorage.getItem('busoutparamcopy');
  const b = JSON.parse(a);
  if (IsEmpty(b) || IsEmpty(a)) {
    VxeMessage('没有要粘贴的数据', VxeNotifyType.warning);
    return;
  }
  if (!methodId.value) {
    VxeMessage('请选择场景', VxeNotifyType.warning);
    return;
  }
  b.forEach((e) => {
    e.interfaceId = interfaceId.value;
    e.methodId = methodId.value;
    e.id = null;
  });
  Object.assign(detailList, b);
}
</script>

<style lang="scss" scoped>
#interMethodOutParamDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>